/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.provider.configuration;


import org.asiainfo.ability.base.utils.StringUtils;
import org.asiainfo.ability.provider.annotation.EnableAbility;
import org.mybatis.spring.mapper.ClassPathMapperScanner;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;


public class AnnotationConfig implements ImportBeanDefinitionRegistrar, ResourceLoaderAware{

    public static String basePackage;




    private ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata
            , BeanDefinitionRegistry beanDefinitionRegistry) {
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(annotationMetadata
                .getAnnotationAttributes(EnableAbility.class.getName()));
        ClassPathMapperScanner scanner = new ClassPathMapperScanner(beanDefinitionRegistry);
        if (this.resourceLoader != null) {
            scanner.setResourceLoader(this.resourceLoader);
        }
        String basePakcage = annoAttrs.getString("basePackage");
        if (StringUtils.isBlank(basePakcage)) {
            basePakcage = annotationMetadata.getClassName().substring(0, annotationMetadata.getClassName()
                    .lastIndexOf("."));
        }

        this.basePackage = basePakcage;

    }

}
